// pages/priceLess/priceLess.js
var app = getApp();
var f = require('../../utils/files.js');
Page({

  /*
      页面的初始数据
   */
  data: {
    freeFirst: false,      //首砍标识
    freeOrderUserList: '',   //帮砍用户列表容器
    FreeNoticeStat: false,  //转发朋友圈蒙板显示状态
    jumptype: '',  //标记来路。默认无值为用户自己的砍价订单详情，有值为帮砍用户显示的订单详情
    lessOk: false,   //是否帮好友完成砍价
    order_detail: '',      //保存订单详情容器
    freeNeed: 0,        //剩余待砍金额
    order_expire: '',    //砍价订单过期日期
    store_detail: '',   //当前订单的商户信息
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    var t = this;
    wx.showLoading({
      title: '数据加载中...',
    })

    var free_id = o.free_id;
    app.GetOpenidObj(f, function (openid_info) {     //获取用户信息对象
      var city_code = app.globalData.CurrentCityObj.code;
      var openid = openid_info.openid;
      if (!openid || !city_code || !free_id) {
        app.A('参数异常！', 1);
        return;
      }
      //一：生成订单号
      var order_number = openid + '_' + city_code + '_' + free_id;
      var file_path = app.globalData.data_path + order_number;
      var order_uri = '/free_order/' + order_number;
      var upyun_path = app.globalData.upyun_shop_cache + order_uri + '.html?tag';
      var upyun_tag1 = app.globalData.upyun_shop_cache + order_uri + '_tag1.html?tag';
      /*
      [0]id  [1]order_numb  [2]openid  [3]intval(free_id)  [4]store_id  [5]title  [6]banner  [7]price  [8]price_free  [9]ctime  [10]stat  [11]tag1
      */

      /*
        ### 003 获取砍价用户列表
        order_numb  string  订单号
        type   bool    true直接从远程获取数据,
      */
      function GetFreeUserList(order_numb, type) {
        var view_user = 0;
        var userListName = '';
        var filePath_user = app.globalData.data_path + 'freeOrderUser_' + order_number;
        var uri_user = '/free_order_user/' + order_number;
        var url_user = app.globalData.upyun_shop_cache + uri_user + '.html';
        if (type) {
          upyun_user();
        } else {
          f.Has(filePath_user, function (s_user) {
            if (s_user == 'ok') {
              f.Reads(filePath_user, function (res_user) {
                if (/^\[\[.*\]\]$/.test(res_user)) {
                  if (view_user) app.C('GetFreeUserList from file is ok');
                  var new_data = JSON.parse(res_user);
                  t.setData({
                    freeOrderUserList: new_data
                  });
                } else {
                  if (view_user) app.C('GetFreeUserList file data format is bad');
                  upyun_user();
                }
              });
            } else {
              if (view_user) app.C('GetFreeUserList file not exists');
              upyun_user();
            }
          });
        }

        function upyun_user() {
          app.Ajax({}, function (upyun_user_res) {
            if (typeof upyun_user_res.data == 'object' && upyun_user_res.data.length > 1) {
              if (view_user) app.C('GetFreeUserList from upyun is ok');
              SaveToFile_user(upyun_user_res.data);
            } else {
              if (view_user) app.C('GetFreeUserList from upyun is bad');
              after_user();
            }
          }, url_user);
        }

        function after_user() {
          if (view_user) app.C('GetFreeUserList from after');
          var data_user = {
            type: 'GetFreeUserList',
            order_numb: order_numb,
            uri: uri_user
          };
          app.Ajax2(data_user, function (res) {
            if (view_user) app.C(res);
            SaveToFile_user(res.data);
          });
        }
        function SaveToFile_user(data) {
          //获取帮砍用户列表
          if (typeof data != 'object' || data.length < 1) {
            if (view_user) app.C('GetFreeUserList 用户列表数据异常');
            return;
          }
          var res_str = JSON.stringify(data);
          f.Writes(filePath_user, res_str, function (s2) {
            if (view_user) app.C('GetFreeUserList saveFile is ' + s2);
            t.setData({
              freeOrderUserList: data
            });
          });
        }
      }  //### 003 获取砍价用户列表结束

      f.Has(file_path, function (s1) {
        var view = 0;
        if (s1 == 'ok') {  //A file缓存存在
          f.Reads(file_path, function (res_file) {
            if (/^\[.+\]$/.test(res_file)) {
              var res_file_obj = JSON.parse(res_file);
              //请求upyun的tag1,并比对
              app.Ajax({}, function (tag1_upyun) {
                var tag1_upyun2 = tag1_upyun.data;
                if (tag1_upyun2 != res_file_obj[11]) {   //如果tag1比对不一致，则upyun或after重新获取数据
                  //判断短时不可重复请求后台
                  if (!wx.getStorageSync(order_number) || wx.getStorageSync(order_number) + 5000 < new Date().getTime()) {
                    if (view) app.C('GetFreeOrderDetail file and upyun tag1 is not same !');
                    Upyun();
                    app.SetStorage(order_number, new Date().getTime());
                    GetFreeUserList(order_number, 1);    //从远程获取帮砍用户列表
                  } else {
                    if (view) app.C('GetFreeOrderDetail from file');
                    SetDataToOrderDetail(res_file_obj);
                  }
                } else {
                  if (view) app.C('GetFreeOrderDetail from file');
                  SetDataToOrderDetail(res_file_obj);
                }
              }, upyun_tag1);
            } else {  //数据格式异常
              if (view) app.C('GetFreeOrderDetail file format is bad!');
              Upyun();
            }
          });
        } else {           //A file缓存不存在
          if (view) app.C('GetFreeOrderDetail file is not exists');
          Upyun();
        }

        function Upyun() {
          app.Ajax({}, function (res_upyun) {
            if (typeof res_upyun.data == 'object' && res_upyun.data.length > 1) {
              if (view) app.C('GetFreeOrderDetail from upyun');
              SaveToFile(res_upyun.data);
            } else {
              if (view) app.C('GetFreeOrderDetail from upyun is bad');
              After();
            }
          }, upyun_path);
        }

        function After() {
          if (view) app.C('GetFreeOrderDetail from after');
          var data = { free_id: free_id, order_number: order_number, openid: openid_info.openid, nickName: openid_info.nickName, headerImg: openid_info.headerImg, type: 'GetOrCreateFreeOrder', order_uri: order_uri };
          app.Ajax2(data, function (res_after) {
            if (typeof res_after.data == 'object' && res_after.data.length > 1) {
              if (res_after.data[11] == 0) {
                res_after.data[11] = 1;
                t.setData({
                  freeFirst: true
                });
              }
              SaveToFile(res_after.data);
            } else {
              SaveToFile('');
            }
          });
        }

        /*
          data   要设置的data数据
          date   服务器的时间
        */
        function SetDataToOrderDetail(data) {     //将订单数据装载到 页面数据 data 中，并获取帮砍用户列表
          wx.hideLoading();
          if (view) app.C(t.data.order_detail);

          //计算当前已砍价和还剩价
          var price = parseFloat(data[7]);
          var freeAlso = parseFloat(data[8]);
          var freeNeed1 = price - freeAlso;     //已砍
          var freeNeed2 = freeNeed1.toFixed(2);  //还剩
          data[6] = data[6] ? app.globalData.upyun_shop_img + data[6] : app.globalData.default_img;

          //计算过期日期
          var expire_date = new Date(data[9] * 1000 + 86400000);
          var tools = require('../../utils/tools.js');
          var order_expire = tools.FormatDate(expire_date);

          //获取商户信息
          var store_id = data[4];
          app.GetStoreOrGoodsDetail(store_id, 'none', function (store_detail) {
            if (typeof store_detail == 'object' && store_detail.length > 1) {
              t.setData({
                order_detail: data,
                freeNeed: freeNeed2,
                order_expire: order_expire,
                store_detail: store_detail
              })
              //app.C(data);

              //获取帮砍用户列表
              GetFreeUserList(data[1]);
            } else {
              if (view) app.C('商户数据异常');
              err_notice(t);
            }
          }, 0, 0);
        }

        function err_notice(t) {
          wx.hideLoading();
          t.setData({
            err_notice: '数据异常！'
          });
        }

        function SaveToFile(data) {
          //app.C(t.data);
          wx.hideLoading();
          //获取帮砍用户列表
          if (typeof data != 'object' || data.length < 1) {
            if (view) app.C('订单数据异常');
            err_notice(t);
            return;
          }
          var res_str = JSON.stringify(data);
          f.Writes(file_path, res_str, function (s2) {
            if (view) app.C('saveFile is ' + s2);
            SetDataToOrderDetail(data);
          });
        }



      });
    });






    return;

    if (o.jumptype) {
      if (o.jumptype == 'me') {
        this.setData({
          jumptype: o.jumptype,
        })
      } else {
        this.setData({
          jumptype: o.jumptype,
        })
      }
    }
  },



  //关闭转发朋友圈蒙板
  HiddenFreeNotice() {
    this.setData({
      FreeNoticeStat: true,  //转发朋友圈蒙板显示状态
    });
  },

  //喊朋友砍一刀
  CallFriendLess() {
    wx.showShareMenu({
      success() {
        console.log('ok')
      }
    })

    return;
    this.setData({
      HiddenForwardStat: false,  //转发朋友圈蒙板显示状态
      jumptype: 'after'
    });
  },

  //帮朋友砍一刀
  HelpFriendLess() {
    this.setData({
      HiddenForwardStat: false,  //转发朋友圈蒙板显示状态
      jumptype: 'HelpFriendLess',
      lessOk: true,
      lessOkStr: '已帮助朋友砍价'
    });
  },




  onShareAppMessage: function () {
    return {
      title: '本地商家活动，砍价免费拿！老铁！快帮我砍一刀！',
      path: '/pages/priceLess/priceLess?jumptype=friend'
    }
  },

  onShow: function () {

  },


  onReachBottom: function () {

  }

})